package com.sun.search.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.sun.commons.pojo.SolrInsertData;
import com.sun.commons.utils.ActionUtils;
import com.sun.dubbo.webmanage.service.TbItemCatDubboService;
import com.sun.dubbo.webmanage.service.TbItemDescDubboService;
import com.sun.dubbo.webmanage.service.TbItemDubboService;
import com.sun.dubbo.webmanage.service.TbSolrSyncLogDubboService;
import com.sun.webmanage.model.TbItem;
import com.sun.webmanage.model.TbItemCat;
import com.sun.webmanage.model.TbItemDesc;
import com.sun.webmanage.model.TbSolrSyncLog;

@Service("SolrSynService")
public class SolrSynServiceImpl implements SolrSynService{

	@Reference
	private TbItemDubboService tbItemDubboService;
	@Reference
	private TbItemCatDubboService tbItemCatDubboService;
	@Reference
	private TbItemDescDubboService tbItemDescDubboService;
	@Reference
	private TbSolrSyncLogDubboService TbSolrSyncLogDubboService;
	
	@Resource
	private CloudSolrClient cloudSolrClient;
	
	private final static Logger LOGGER = LoggerFactory.getLogger(SolrSynService.class);
	
	@Override
	public Map<String, Object> initData(boolean is_all) {
		Date now = new Date();
		long start = System.currentTimeMillis();
		Date startDate = null;
		
		List<TbSolrSyncLog> logList = TbSolrSyncLogDubboService.selectSolrSyncLogNewByType((byte)4);
		if((logList==null || logList.isEmpty()) || is_all){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				 startDate = sdf.parse("2010-01-01 00:00:00");
			} catch (ParseException e) {
				e.printStackTrace();
				LOGGER.error("同步solr信息失败，error==="+e.getMessage());
			}
		}else{
			startDate = logList.get(0).getCreated();
		}
		
		
		
		List<TbItem> listdata = tbItemDubboService.selectAllByStatusCreateTime((byte)1, startDate, now);
		SolrInputDocument docs = null;
		TbItemDesc tbItemDesc = null;
		TbItemCat tbItemCat = null;
		/**
		 *  <field name="item_title" type="text_ik" indexed="true" stored="true"/>
			<field name="item_sell_point" type="text_ik" indexed="true" stored="true"/>
			<field name="item_price"  type="long" indexed="true" stored="true"/>
			<field name="item_image" type="string" indexed="false" stored="true" />
			<field name="item_category_name" type="string" indexed="true" stored="true" />
			<field name="item_desc" type="text_ik" indexed="true" stored="false" />
		 * */
		for (TbItem tbItem : listdata) {
			 tbItemDesc = tbItemDescDubboService.selectTbItemDescByItemId(tbItem.getId());
			 tbItemCat = tbItemCatDubboService.loadTbItemCatByPK(tbItem.getCid());
			docs = new SolrInputDocument();
			docs.addField("id", tbItem.getId());
			docs.addField("item_title", tbItem.getTitle());
			docs.addField("item_sell_point", tbItem.getSellPoint());
			docs.addField("item_price", tbItem.getPrice());
			docs.addField("item_image", tbItem.getImage());
			docs.addField("item_category_name", tbItemCat.getName());
			docs.addField("item_desc", tbItemDesc.getItemDesc());
			
			try {
				cloudSolrClient.add(docs);
			} catch (Exception e) {
				e.printStackTrace();
				LOGGER.error("同步solr信息失败，error==="+e.getMessage());
			} 
		}
		try {
			cloudSolrClient.commit();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("同步solr信息失败，error==="+e.getMessage());
		} 
		
		long end = System.currentTimeMillis();
		
		if(listdata.size()>0){
		TbSolrSyncLog log = new TbSolrSyncLog();
		log.setOperaType((byte)4);
		log.setCreated(now);
		long operatime = end-start;
		log.setOperaTime(operatime);
		log.setOperator(0L);
		log.setOperatorName("管理员");
		log.setInfluence(Long.valueOf(listdata.size()));//更新条目数
		int inc = TbSolrSyncLogDubboService.insertSolrSyncLog(log);
		if(inc>0){
			return ActionUtils.ajaxSuccess("同步solr索引信息成功", "更新条目数："+listdata.size()+",操作时间："+(operatime/1000)+"s");
		}
		}else{
			return ActionUtils.ajaxSuccess("同步solr索引信息成功", "暂无数据需要更新");
		}
		
		//同步数据   记录日志  规范返回格式   状态+信息+操作时间
		return ActionUtils.ajaxFail("同步solr索引信息失败", "");
	}
	

	@Override
	public boolean insertData(SolrInsertData solrInsetData) {
		Date now = new Date();
		long start = System.currentTimeMillis();
		SolrInputDocument docs = new SolrInputDocument();
		docs.addField("id", solrInsetData.getId());
		docs.addField("item_title", solrInsetData.getItem_title());
		docs.addField("item_sell_point", solrInsetData.getItem_sell_point());
		docs.addField("item_price", solrInsetData.getItem_price());
		docs.addField("item_image", solrInsetData.getItem_image());
		docs.addField("item_category_name", solrInsetData.getItem_category_name());
		docs.addField("item_desc", solrInsetData.getItem_desc());
		
		try {
			cloudSolrClient.add(docs);
			cloudSolrClient.commit();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("同步solr信息失败，error==="+e.getMessage());
		} 
		
		long end = System.currentTimeMillis();
		
		TbSolrSyncLog log = new TbSolrSyncLog();
		log.setOperaType((byte)1);
		log.setCreated(now);
		long operatime = end-start;
		log.setOperaTime(operatime);
		log.setOperator(0L);
		log.setOperatorName("管理员");
		log.setInfluence(1L);//更新条目数
		int inc = TbSolrSyncLogDubboService.insertSolrSyncLog(log);
		if(inc>0){
			return true;
		}
		//同步数据   记录日志  规范返回格式   状态+信息+操作时间
		return false;
	}

	@Override
	public boolean updateData(SolrInsertData solrInsetData) {
		Date now = new Date();
		long start = System.currentTimeMillis();
		SolrInputDocument docs = new SolrInputDocument();
		docs.addField("id", solrInsetData.getId());
		docs.addField("item_title", solrInsetData.getItem_title());
		docs.addField("item_sell_point", solrInsetData.getItem_sell_point());
		docs.addField("item_price", solrInsetData.getItem_price());
		docs.addField("item_image", solrInsetData.getItem_image());
		docs.addField("item_category_name", solrInsetData.getItem_category_name());
		docs.addField("item_desc", solrInsetData.getItem_desc());
		
		try {
			cloudSolrClient.add(docs);
			cloudSolrClient.commit();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("同步solr信息失败，error==="+e.getMessage());
		} 
		
		long end = System.currentTimeMillis();
		TbSolrSyncLog log = new TbSolrSyncLog();
		log.setOperaType((byte)2);
		log.setCreated(now);
		long operatime = end-start;
		log.setOperaTime(operatime);
		log.setOperator(0L);
		log.setOperatorName("管理员");
		log.setInfluence(1L);//更新条目数
		int inc = TbSolrSyncLogDubboService.insertSolrSyncLog(log);
		if(inc>0){
			return true;
		}
		//同步数据   记录日志  规范返回格式   状态+信息+操作时间
		return false;
	}

	@Override
	public boolean deleteDate(List<String> ids) {
		Date now = new Date();
		long start = System.currentTimeMillis();
		try {
			cloudSolrClient.deleteById(ids);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		try {
			cloudSolrClient.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		TbSolrSyncLog log = new TbSolrSyncLog();
		log.setOperaType((byte)3);
		log.setCreated(now);
		long operatime = end-start;
		log.setOperaTime(operatime);
		log.setOperator(0L);
		log.setOperatorName("管理员");
		log.setInfluence(Long.valueOf(ids.size()));//更新条目数
		int inc = TbSolrSyncLogDubboService.insertSolrSyncLog(log);
		if(inc>0){
			return true;
		}
		//同步数据   记录日志  规范返回格式   状态+信息+操作时间
		return false;
	}

}
